# -*- coding: utf-8 -*-
'''
Copyright (C) 2011 olejl77@gmail.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''

# Description about the VGTV API can be found here:
# http://www.vgtv.no/api/?topic=feeds

import urllib
import re
import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
from BeautifulSoup import BeautifulSoup
from Item import Item

__settings__ = xbmcaddon.Addon(id="plugin.video.no.vg")
__language__ = __settings__.getLocalizedString
quality = __settings__.getSetting("quality")

def createMainMenu(baseUrl, handle):
	listing = []
	listing.append(Item(title=__language__(30021),url=baseUrl+'?select=bookmarks'))
	listing.append(Item(title=__language__(30022),url=baseUrl+'?select=category'))
	listing.append(Item(title=__language__(30023),url=baseUrl+'?select=search'))
	listing.append(Item(title=__language__(30024),url=baseUrl+'?select=recent'))
	sendToXbmc(handle, listing)

def createCategoryMenu(baseUrl, handle):
	listing = []
	url = 'http://www.vgtv.no/api/?do=feed&action=categories'
	soup = BeautifulSoup(urllib.urlopen(url))

	items = soup.findAll('item')
	for item in items:
		cat_id = item.id.contents[0]
		title = item.findAll('name')[0].contents[0]
		order = item.order.contents[0]
		videocount = item.videocount.contents[0]

		title = '%s (videos: %s)' % (title, videocount)

		listing.append(Item(title=title,url=baseUrl+"?sub=" + cat_id))

	sendToXbmc(handle, listing)

def createPlaylistMenu(baseUrl, handle, url):
	listing = []
	soup = BeautifulSoup(urllib.urlopen(url))

	items = soup.findAll('item')
	for item in items:
		video_id = item.id.contents[0]
		cat_id = item.categoryid.contents[0]
		title = item.title.contents[0]
		date = item.pubdate.contents[0]
		#videocount = item.videocount.contents[0]
		description = item.description.contents[0]
		duration = item.duration.contents[0]
		thumb = item.image['url']

		url ='http://www.vgtv.no/api/?do=playlist&id=%s' % (video_id)
		tmp_soup = BeautifulSoup(urllib.urlopen(url))
		url = tmp_soup.tracklist.track.location.contents[0]
		print quality
		if quality == 0:
			url = tmp_soup.find('tv:lowbandwidthlocation').contents[0]
		else:
			url = tmp_soup.find('location').contents[0]

		listing.append(Item(
			title=title,
			url=url,
			thumb=thumb,
			description=description,
			date=date,
			duration=duration,
			isPlayable=True
		))

	sendToXbmc(handle, listing)

def sendToXbmc(handle, listing):
	"""
	Sends a listing to XBMC for display as a directory listing
	Plugins always result in a listing
	"""
	# send each item to xbmc
	for item in listing:
		listItem = xbmcgui.ListItem(item.title, thumbnailImage=item.thumb)
		listItem.setInfo(
			type='Video',
			infoLabels={
				'title': item.title, 
				'plot':item.description,
				'duration':item.duration,
				'rating':int(item.rating),
				'playcount':int(item.viewed),
				'date':item.date,
				'votes':item.votes,
				'Property(releasedate)':item.fanart	# TODO not sure about this one ...
			})
		xbmcplugin.addDirectoryItem(handle, item.url, listItem, not item.isPlayable)

	# tell xbmc we have finished creating the directory listing
	xbmcplugin.endOfDirectory(handle)

if ( __name__ == "__main__" ):
	xbmcplugin.setContent(int(sys.argv[1]), "episodes")
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)

	# Probaly not the "correct way...
	# sys.argv[2]: ?sub=<category id>=<offset>
	# Offset is used to paginate the movies within a category
	arg = sys.argv[2].split('=')

	if (arg[0] == "?select"):
		if arg[1] == 'category':
			createCategoryMenu(sys.argv[0], int(sys.argv[1]))
		elif arg[1] == 'recent':
			url = 'http://www.vgtv.no/api/?do=feed&action=recent'
			createPlaylistMenu(sys.argv[0], int(sys.argv[1]), url)
		elif arg[1] == 'search':
			kb = xbmc.Keyboard()
			kb.doModal()
			if (kb.isConfirmed()):
				text = kb.getText()
				url = 'http://www.vgtv.no/api/?do=feed&action=search&value=%s' % (text)
				createPlaylistMenu(sys.argv[0], int(sys.argv[1]), url)
	elif (arg[0] == "?sub"):
		url = 'http://www.vgtv.no/api/?do=feed&action=category&value=%s' % (arg[1])
		createPlaylistMenu(sys.argv[0], int(sys.argv[1]), url)
	else:
		createMainMenu(sys.argv[0], int(sys.argv[1]))

